<template>
    <div>
        <!--卡片-->
        <el-card class="box-card">
            <!--定义面包屑-->
            <el-breadcrumb separator=">">
                <el-breadcrumb-item :to="{ path: '/homePage' }">首页</el-breadcrumb-item>
                <el-breadcrumb-item>系统管理</el-breadcrumb-item>
                <el-breadcrumb-item>用户管理</el-breadcrumb-item>
            </el-breadcrumb>
            <el-divider></el-divider>
            <!--表单的搜索框
                 :model="双向绑定表单的数据"
            -->
            <el-form :inline="true" :model="queryUserData"  class="demo-form-inline">
                <el-form-item >
                    <el-input v-model="queryUserData.loginname" placeholder="请输入登陆名"></el-input>
                </el-form-item>
                <el-form-item >
                    <el-input v-model="queryUserData.username" placeholder="请输入用户名"></el-input>
                </el-form-item>
                <el-form-item >
                    <el-input v-model="queryUserData.email" placeholder="请输入用户邮箱"></el-input>
                </el-form-item>
                <el-form-item >
                    <el-input v-model="queryUserData.phone" placeholder="请输入用户手机号"></el-input>
                </el-form-item>
                <el-form-item>
                    <el-button type="primary" @click="showAllUser()">查询</el-button>
                    <el-button type="primary" @click="showUserForm()">添加</el-button>
                </el-form-item>
            </el-form>

            <!--数据表格-->
            <template>
                <el-table
                        :data="tableData"
                        :border="true"
                        stripe
                        style="width: 100%">
                    <el-table-column
                            prop="userid"
                            label="编号">
                    </el-table-column>
                    <el-table-column
                            prop="loginname"
                            label="用户登录名">
                    </el-table-column>
                    <el-table-column
                            prop="username"
                            label="用户名">
                    </el-table-column>
                    <el-table-column
                            prop="email"
                            label="用户邮箱">
                    </el-table-column>
                    <el-table-column
                            prop="phone"
                            label="用户手机号">
                    </el-table-column>
                    <el-table-column
                            prop="sex"
                            label="用户性别"
                    width="80">
                        <template slot-scope="scope">
                            <span v-if="scope.row.sex==0">女</span>
                            <span v-if="scope.row.sex==1">男</span>
                        </template>
                    </el-table-column>
                    <el-table-column
                            prop="url"
                            label="用户头像">
                        <template slot-scope="scope">
                            <el-avatar shape="square" :size="50" :src="scope.row.url"></el-avatar>
                        </template>
                    </el-table-column>
                    <el-table-column
                            prop="salt"
                            label="用户加密盐值">
                    </el-table-column>
                    <el-table-column
                            prop="status"
                            label="状态">
                        <template slot-scope="scope">
                            <el-switch
                                    v-model="scope.row.status"
                                    active-color="#13ce66"
                                    active-value="0"
                                    inactive-value="1"
                                    inactive-color="#ff4949"
                                    @change="statusChange(scope.row)">
                            </el-switch>
                        </template>
                    </el-table-column>
                    <!--<el-table-column-->
                            <!--prop="loginIp"-->
                            <!--label="用户登录时的ip地址">-->
                    <!--</el-table-column>-->
                    <!--<el-table-column-->
                            <!--prop="loginDate"-->
                            <!--label="用户登录时的时间">-->
                    <!--</el-table-column>-->
                    <el-table-column
                            prop="createBy"
                            label="创建者">
                    </el-table-column>
                    <el-table-column
                            prop="createTime"
                            label="创建时间">
                    </el-table-column>
                    <el-table-column
                            prop="updateBy"
                            label="修改者">
                    </el-table-column>
                    <el-table-column
                            prop="updateTime"
                            label="修改时间">
                    </el-table-column>
                    <el-table-column label="操作" width="180">
                        <template slot-scope="scope">
                            <!-- 修改 -->
                            <el-button type="primary" icon="el-icon-edit" circle @click="updateUserByUserid(scope.row)"></el-button>
                            <!-- 删除 -->
                            <el-button type="danger" icon="el-icon-delete" circle @click="delUserByUserid(scope.row.userid)"></el-button>
                            <!-- 分配角色 -->
                            <el-button type="warning" icon="el-icon-star-off" circle @click="showUserHasRole(scope.row.userid)"></el-button>
                        </template>
                    </el-table-column>
                </el-table>
                <!-- 分页 -->
                <el-pagination
                        @size-change="handleSizeChange"
                        @current-change="handleCurrentChange"
                        :current-page="currentPage"
                        :page-sizes="[5, 7, 9]"
                        :page-size="pageSize"
                        layout="total, sizes, prev, pager, next, jumper"
                        :total="total">
                </el-pagination>
            </template>
            <!-- 修改用户的角色 -->
            <div>
                <el-dialog
                        title="修改用户的角色"
                        :visible.sync="showRole"
                        width="30%">
                <span>
                    <el-checkbox-group v-model="userHasRole" size="small">
                        <el-checkbox-button v-for="role in allRole" :label="role.roleId" :key="role.roleId" border>{{role.roleName}}</el-checkbox-button>
                    </el-checkbox-group>
                </span>
                    <span slot="footer" class="dialog-footer">
                    <el-button @click="showRole = false">取 消</el-button>
                    <el-button type="primary" @click="updateUserHasRole">确 定</el-button>
                </span>
                </el-dialog>
            </div>
            <!-- 新增用户 -->
            <div>
                <el-dialog
                        title="新增用户"
                        :visible.sync="addUserForm"
                        width="30%">
                <span>
                    <el-form label-position="left" label-width="80px" :model="addUserDate" :rules="userFormRules" ref="userForm">
                      <!-- 用户id，修改时使用，隐藏 -->
                      <el-input v-model="addUserDate.userid" type="hidden"></el-input>
                      <el-form-item label="登录名" prop="loginname">
                        <el-input v-model="addUserDate.loginname"></el-input>
                      </el-form-item>
                      <el-form-item label="用户昵称" prop="username">
                        <el-input v-model="addUserDate.username"></el-input>
                      </el-form-item>
                      <el-form-item label="用户密码" prop="userpwd">
                        <el-input v-model="addUserDate.userpwd" v-if="addUserDate.userid == null" type="password"></el-input>
                        <el-input v-model="addUserDate.userpwd " readonly="readonly" v-if="addUserDate.userid != null"></el-input>
                      </el-form-item>
                        <el-form-item label="用户邮箱" prop="email">
                        <el-input v-model="addUserDate.email"></el-input>
                      </el-form-item>
                      <el-form-item label="用户手机号" prop="phone">
                        <el-input v-model="addUserDate.phone"></el-input>
                      </el-form-item>
                      <el-form-item label="用户性别" prop="sex">
                        <el-radio-group v-model="addUserDate.sex">
                          <el-radio label="1">男</el-radio>
                          <el-radio label="0">女</el-radio>
                        </el-radio-group>
                      </el-form-item>
                      <el-form-item label="用户头像">
                        <el-upload
                                class="avatar-uploader"
                                action="http://192.168.0.100:80/clms-system/user/upload"
                                :headers= "headers"
                                :show-file-list="false"
                                :on-success="handleAvatarSuccess"
                                :before-upload="beforeAvatarUpload">
                           <img v-if="imageUrl" :src="imageUrl" class="avatar">
                           <i v-else class="el-icon-plus avatar-uploader-icon"></i>
                        </el-upload>
                      </el-form-item>
                    </el-form>
                </span>
                    <span slot="footer" class="dialog-footer">
                    <el-button @click="addUserForm = false">取 消</el-button>
                    <el-button type="primary" @click="addUser('userForm')">确 定</el-button>
                </span>
                </el-dialog>
            </div>

        </el-card>
    </div>
</template>

<script>
    export default {
        name: "Users",
        data() {
            return {
                headers: {
                  'Token' : sessionStorage.getItem("token")
                },
                queryUserData: {
                    loginname: '',
                    username: '',
                    email: '',
                    phone: '',
                },
                tableData: [],
                addUserDate: {
                    userid: '',
                    loginname: '',
                    username: '',
                    email: '',
                    phone: '',
                    sex: '',
                    url: '',
                    userpwd: '',
                },
                userFormRules: {
                    loginname: [
                        { required: true, message: '请输入登录名', trigger: 'blur' },
                        { min: 2, max: 10, message: '长度在 2 到 10 个字符', trigger: 'blur' }
                    ],
                    username: [
                        { required: true, message: '请输入用户名', trigger: 'blur' },
                        { min: 2, max: 10, message: '长度在 2 到 10 个字符', trigger: 'blur' }
                    ],
                    email: [
                        { required: true, message: '请输入邮箱', trigger: 'blur' },
                        { type: 'email', message: '请输入正确的邮箱地址', trigger: ['blur', 'change'] }
                    ],
                    phone: [
                        { required: true, message: '请输入手机号', trigger: 'blur' },
                        { min: 11, max: 11, message: '手机号格式不正确，11位', trigger: 'blur' }
                    ],
                    sex: [
                        { required: true, message: '请选择性别', trigger: 'blur' }
                    ],
                    userpwd:[
                        { required: true, message: '请输入密码', trigger: 'blur' },
                        { min: 3, max: 20, message: '长度在 3 到 20 个字符', trigger: 'blur' }
                    ],
                },
                pageSize: 5,
                currentPage: 1,
                total: 0,
                showRole: false,
                addUserForm: false,
                imageUrl: '',
                allRole: [],
                userHasRole: {},
                userid: ''
            }
        },
        methods:{
            handleSizeChange(value) {
                this.pageSize = value;
                this.showAllUser();
            },
            handleCurrentChange(value) {
                this.currentPage = value;
                this.showAllUser();
            },
            // 状态改变时触发
            statusChange(row) {
                // 修改用户的状态
                this.$axios({
                    method: 'get',
                    url: 'clms-system/user/updateStatus',
                    params: {
                        userid: row.userid,
                        status: row.status
                    }
                }).then( result => {
                    if (result.data.code == 200) {
                        this.$message.success(result.data.message);
                        this.showAllUser()
                    } else {
                        this.$message.error(result.data.message)
                    }
                })
            },
            // 查询全部的用户信息
            showAllUser() {
                this.$axios({
                    method: 'get',
                    url: 'clms-system/user/showAllUser',
                    params: {
                        loginname: this.queryUserData.loginname,
                        username: this.queryUserData.username,
                        email: this.queryUserData.email,
                        phone: this.queryUserData.phone,
                        pageno: this.currentPage,
                        pagesize: this.pageSize
                    }
                }).then( result => {
                    this.tableData = result.data.listData;
                    this.total = result.data.object.total
                })
            },
            // 查询全部的角色信息
            showAllRole() {
                this.$axios({
                    method: 'get',
                    url: 'clms-system/role/showAllRole',
                }).then( result => {
                    this.allRole = result.data.listData;
                })
            },
            // 查询用户拥有的角色
            showUserHasRole(userid) {
                this.showRole = true;
                this.userid = userid;
                this.$axios({
                    method: 'get',
                    url: 'clms-system/role/showUserHasRole',
                    params: {
                        userid : this.userid
                    }
                }).then( result => {
                    this.userHasRole = result.data.listData
                })
            },
            showUserForm() {
                this.addUserForm = true;
                this.addUserDate = {};
                this.imageUrl = ''
            },
            // 修改用户的角色信息
            updateUserHasRole() {
                this.$axios({
                    method: 'get',
                    url: 'clms-system/role/updateUserHasRole?roleidList='+this.userHasRole,
                    params: {
                        userid: this.userid
                    }
                }).then( result => {
                    this.$message.success(result.data.message);
                    this.showRole = false;
                })
            },
            // 新增用户
            addUser(formName) {
                this.$refs[formName].validate((valid) => {
                    if (valid) {
                        if (this.addUserDate.userid == null ) {
                            // 执行新增
                            this.$axios({
                                method: 'post',
                                url: 'clms-system/user/addUser',
                                data: this.addUserDate
                            }).then( result => {
                                if (result.data.code == 200) {
                                    this.$message.success(result.data.message);
                                    this.addUserForm = false;
                                    this.showAllUser()
                                } else {
                                    this.$message.error(result.data.message)
                                }
                            })
                        } else {
                            // 执行修改
                            this.$axios({
                                method: 'post',
                                url: 'clms-system/user/updateUser',
                                data: this.addUserDate
                            }).then( result => {
                                if (result.data.code == 200) {
                                    this.$message.success(result.data.message);
                                    this.showAllUser();
                                    this.addUserForm = false;
                                } else {
                                    this.$message.error(result.data.message)
                                }
                            })
                        }
                    } else {
                        this.$message.error("数据校验有误！");
                    }
                });
            },
            // 删除用户
            delUserByUserid(userid) {
                this.$confirm('确实删除当前用户吗?', '提示', {
                    confirmButtonText: '确定',
                    cancelButtonText: '取消',
                    type: 'warning'
                }).then(() => {
                    // 判断当前用户是不是管理员
                    this.$axios({
                        method: 'get',
                        url: 'clms-system/role/isAdmin',
                        params: {
                            userid: userid
                        }
                    }).then( result => {
                        if (result.data.object == true) {
                            this.$message.error("当前用户是管理员，无法删除");
                        } else {
                            this.$axios({
                                method: 'get',
                                url: 'clms-system/user/delUserByUserid',
                                params: {
                                    userid: userid
                                }
                            }).then( result => {
                                if (result.data.code == 200) {
                                    this.$message.success(result.data.message);
                                    this.showAllUser()
                                } else {
                                    this.$message.error(result.data.message)
                                }
                            })
                        }
                    });
                })
            },
            // 修改用户,渲染form表单
            updateUserByUserid(row) {
                this.addUserForm = true;
                row.userpwd = "******";
                this.addUserDate = row;
                // 头像回显
                this.imageUrl = this.addUserDate.url;
            },
            // 上传图片成功后的钩子函数
            handleAvatarSuccess(response, file) {
                this.addUserDate.url = response.img;
                this.imageUrl = URL.createObjectURL(file.raw);
            },
            beforeAvatarUpload(file) {
                const isJPG = file.type === 'image/jpeg';
                const isLt2M = file.size / 1024 / 1024 < 2;
                if (!isJPG) {
                    this.$message.error('上传头像图片只能是 JPG 格式!');
                }
                if (!isLt2M) {
                    this.$message.error('上传头像图片大小不能超过 2MB!');
                }
                return isJPG && isLt2M;
            }
        },
        created() {
            this.showAllUser();
            this.showAllRole()
        }
    }
</script>

<style>
    .avatar-uploader .el-upload {
        border: 1px dashed #d9d9d9;
        border-radius: 6px;
        cursor: pointer;
        position: relative;
        overflow: hidden;
    }
    .avatar-uploader .el-upload:hover {
        border-color: #409EFF;
    }
    .avatar-uploader-icon {
        font-size: 28px;
        color: #8c939d;
        width: 178px;
        height: 178px;
        line-height: 178px;
        text-align: center;
    }
    .avatar {
        width: 178px;
        height: 178px;
        display: block;
    }
</style>